package com.idp.web.security.config;

import com.idp.web.security.handle.AuthenticationEntryPointImpl;
import com.idp.web.security.handle.JwtAuthenticationTokenFilter;
import com.idp.web.security.handle.LogoutSuccessHandlerImpl;
import com.idp.web.security.provider.AppUserAuthenticationProvider;
import com.idp.web.security.provider.PhoneAuthenticationProvider;
import com.idp.web.security.provider.SysUserAuthenticationProvider;
import com.idp.web.security.provider.WechatAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * spring security配置
 * @author king
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;
    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;
    @Autowired
    private CorsFilter corsFilter;
    @Autowired
    private AnonymousUrlsConfig anonymousUrlsConfig;
    @Autowired
    private SysUserAuthenticationProvider sysUserAuthenticationProvider;
    @Autowired
    private AppUserAuthenticationProvider appUserAuthenticationProvider;
    @Autowired
    private PhoneAuthenticationProvider phoneAuthenticationProvider;
    @Autowired
    private WechatAuthenticationProvider wechatAuthenticationProvider;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // 匿名访问的url
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
        anonymousUrlsConfig.getUrls().forEach(url -> registry.antMatchers(url).permitAll());

        httpSecurity
                // CSRF禁用，因为不使用session
                .csrf().disable()
                .formLogin().disable()
                // 禁用HTTP响应标头
                .headers().cacheControl().disable().and()
                .headers().frameOptions().disable().and()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录、注册、获取验证码 允许匿名访问
                .antMatchers("/login/login", "/login/getCaptcha").permitAll()
                .antMatchers("/appLogin/loginPwd", "/appUser/registerUser").permitAll()
                .antMatchers("/appLogin/loginSms", "/appLogin/getSmsCode", "/appLogin/checkSmsCode").permitAll()
                .antMatchers("/appLogin/loginWechat", "/appLogin/loginWechatAuthBase").permitAll()
                // 静态资源，可匿名访问
                .antMatchers(HttpMethod.GET, "/", "/**.html", "/**.css", "/**.js", "/**.ico", "/**/showFile").permitAll()
                .antMatchers("/v2/api-docs", "/swagger-ui.html", "/swagger-resources/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                // 认证失败处理类
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 退出登录处理类
                .logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler).and()
                // token验证
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                // CORS过滤器
                .addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class)
                .addFilterBefore(corsFilter, LogoutFilter.class);

    }

    /**
     * 身份认证
     * @param auth
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) {

        auth.authenticationProvider(sysUserAuthenticationProvider)
            .authenticationProvider(appUserAuthenticationProvider)
            .authenticationProvider(phoneAuthenticationProvider)
            .authenticationProvider(wechatAuthenticationProvider);
    }
}
